import { bankcardApplyUrl, bankcardDetailUrl, bankCardOCRUrl } from '../../../../api/individual'
import { post, uploadFile, initUploadFileListKey, getMessageAuth } from '../../../../utils/index'
import WxValidate from '../../../../utils/WxValidate'

Page({
  data: {
    info: {},
    form: {},
    formError: {}
  },
  async loadData () { // 获取申请详情
    const { data: info, data: { dispatchBankCardBriefVO: data } } = await post(bankcardDetailUrl)
    data.newBankCode = info.bankDictKey
    if (data.id) {
      data.img = `../../../../assets/img/${data.status ? 'checkFail' : 'checking'}_img.png`
      data.title = data.status ? '办理失败' : '等待处理'
      data.subTitle = data.status ? data.msg : '已提交审核，等待工作人员处理'
      data.newBankCardImgList = [{ url: data.newBankCardImgAddress, name: '银行卡图片' }]
    }
    this.setData({ form: data, info })
  },
  async submit () { // 申请
    const { form } = this.data
    if (!this.WxValidate.checkForm(form)) {
      const formError = this.WxValidate.formError
      this.setData({ formError })
      wx.showToast({ title: '信息填写有误，请检查', icon: 'none' })
      return
    }
    await post(bankcardApplyUrl, form)
    this.loadData()
    getMessageAuth()
  },
  edit () { // 重新编辑
    this.setData({ 'form.status': '' })
  },
  newBankCardNoChange ({ detail }) { // 请输入银行卡号
    this.data.form.newBankCardNo = detail
  },
  async newBankCardImgRead ({ detail }) { // 银行卡上传
    const { file } = detail
    this.setData({ formError: {} })
    let { data } = await uploadFile(file.path)
    data = initUploadFileListKey(data)
    this.setData({ 'form.newBankCardImgList': [data] })
    this.data.form.newBankCardImg = data.link
    this.data.form.newBankCardImgId = data.id
    this.bankCardOCR()
  },
  newBankCardImgDel () { // 银行卡删除
    this.data.form.newBankCardImg = ''
    this.data.form.newBankCardImgId = ''
    this.setData({ 'form.newBankCardImgList': [] })
  },
  async bankCardOCR () { // 银行卡ocr
    const { form, info } = this.data
    const { data } = await post(bankCardOCRUrl, { path: form.newBankCardImg }, {}, false)
    if (data.bankName !== info.bankDictValue) {
      wx.showToast({ title: `请上传${info.bankDictValue}的银行卡`, icon: 'none' })
      this.setData({ 'formError.bankName': `请上传${info.bankDictValue}的银行卡` })
      return
    }
    this.setData({ 'form.newBankCardNo': data.bankCardNo })
  },
  initValidator () { // 初始化验证器
    const rules = {
      newBankCardNo: { required: true },
      newBankCardImgId: { required: true }
    }
    const messages = {
      newBankCardNo: { required: '请输入工资卡号' },
      newBankCardImgId: { required: '请上传银行卡复印件' }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  onLoad () {
    this.loadData()
    this.initValidator()
  },
  onPullDownRefresh () {
    const { status } = this.data.form
    if (status === 0 || status === 2) {
      this.loadData()
    }
  }
})